import { persistentWritable } from '$utils/persist';
import { onMount } from 'svelte';
import type { Writable } from 'svelte/store';

type CartItem = Partial<Product.Detail>;

type CartListType = CartItem[];

const getDefaultCart = (): CartListType => [];

type PreOrderHookResultType = {
	preOrderList: Writable<IdListType>;
	placeTime: Writable<number>;
	setPreOrders: (items: IdListType) => void;
};
type IdListType = string[];

export const usePreOrderStore = () => {
	const preOrderList = persistentWritable<IdListType>('preOrderList', getDefaultCart());
	const placeTime = persistentWritable<number>('placeTime', 0); // 下单时间

	const setPreOrders = (items: IdListType) => {
		preOrderList.update(() => {
			const result = [...items.filter((id) => !isNaN(+id))]; // 过滤掉非数字id
			return [...new Set(result)];
		});
	};

	return {
		preOrderList,
		placeTime,
		setPreOrders
	};
};

export const getPreOrderStore = () => {
	const result: IObject = {};

	const merge_store = () => Object.assign(result, usePreOrderStore());

	onMount(merge_store);

	return result as unknown as PreOrderHookResultType;
};
